package com.itmck.service;

import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Component;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;

@Component
public class CommonServiceImpl implements CommonService {


    @Resource
    private UserService userService;

    @Resource
    private UserService2 userService2;


    @Resource
    private TransactionTemplate transactionTemplate;


    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public void add() {
        userService.addRequiresNew();
        userService2.addRequiresNew();
        throw new RuntimeException("异常");

    }

    @Override
    public void update() {


        transactionTemplate.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(@NotNull TransactionStatus transactionStatus) {
                try {
                    userService2.addRequiresNew();
                } catch (Exception e) {
                    transactionStatus.setRollbackOnly();
                }
            }
        });

        transactionTemplate.executeWithoutResult(transactionStatus -> userService.addRequiresNew());
    }
}
